import React from "react";
import { connectToUser } from "./connecters/connectTouser-2.js";
import { appContext, connect, createStore } from './redux-6.jsx';

// reduce 用于规范 state 创建流程的函数
const reducer = (state, {type, payload = {}}) => {
    if (type === 'updateUser') {
        return {
            ...state,
            user: {
                ...state.user,
                ...payload
            }
        }
    } else {
        return state;
    }
}
const initState = {
    user: {
        name: 'tom',
        age: 99
    },
    group: {
        name: '航海网'
    }
};
const store = createStore(reducer, initState);

const User = connectToUser(({user}) => {
    console.log('User 组件')
    return (
        <div>
            User: {user.name}
        </div>
    );
})

const UserModifier = connectToUser(({updateUser, user, children}) => {
    console.log('UserModifier 组件')
    const changeHandler = (e) => {
        updateUser({
            name: e.target.value
        });
    }
    return (
        <div>
            {children}
            <input type="text" value={user.name} onChange={changeHandler}/>
        </div>
    );
});

const A = () => {
    console.log('A 组件')
    return <section>A 组件<User/></section>;
}
const B = () => {
    console.log('B 组件')
    return <section>B 组件<UserModifier num={1}>DDD</UserModifier></section>;
}
const C = connect(state => {
    return {
        group: state.group
    }
})(({group}) => {
    console.log('C 组件');
    return <section>C 组件 = <p>Group: {group.name}</p></section>;
})

function App() {
    return (
        <appContext.Provider value={store}>
            <A/>
            <B/>
            <C/>
        </appContext.Provider>
    );
}

export default App;